from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models import QuerySet

from backend.utils.redis_utils import RedisUtils


class NotDeletedManager(models.Manager.from_queryset(QuerySet)):
    def get_queryset(self, ignore_deleted=False):
        if ignore_deleted:
            return super().get_queryset()

        return super(NotDeletedManager, self).get_queryset().filter(is_delete=False).order_by(
            "-update_time")


# Create your models here.
class User(AbstractUser):
    mobile = models.CharField(max_length=15, unique=True, verbose_name='手机号')
    home_path = models.CharField(max_length=255, verbose_name='跳转路径')
    real_name = models.CharField(max_length=255, verbose_name='跳转路径')
    desc = models.CharField(max_length=255, verbose_name='用户描述')
    avatar = models.ImageField(upload_to="avatar/%Y", null=True, default="", verbose_name="个人头像")
    is_delete = models.BooleanField(default=False, verbose_name="是否删除")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    create_by = models.ForeignKey('self', on_delete=models.CASCADE, default=1, verbose_name='创建人',
                                  related_name='created_users')
    modified_by = models.ForeignKey('self', on_delete=models.CASCADE, default=1, verbose_name='修改人',
                                    related_name='modified_users')

    advanced_objects = NotDeletedManager()

    class Meta:
        db_table = 'users'
        verbose_name = '用户信息'
        verbose_name_plural = verbose_name

    def set_permission_code(self):
        from permissions.models import Menu
        if self.is_superuser:
            permission_code = set(Menu.advanced_objects.all().values_list('code', flat=True))
        else:
            role_id_list = self.roles.values_list('id', flat=True)
            permission_code = set(
                Menu.advanced_objects.filter(roles__id__in=role_id_list).values_list('code', flat=True))
        permission_code = list(permission_code)
        self.permission_code = permission_code
        RedisUtils("permission").write_value_as_string(f'permission_code_{self.pk}', permission_code, 60 * 60 * 30)

    def has_permission_code(self, code):
        self.get_permission_code()
        return self.permission_code.count(code) > 0

    def get_permission_code(self):
        permission_code = RedisUtils('permission').read_value_to_object(f'permission_code_{self.pk}')
        if not permission_code:
            self.set_permission_code()
        else:
            self.permission_code = permission_code
        return self.permission_code


class File(models.Model):
    name = models.CharField(max_length=255, verbose_name='文件名')
    file = models.FileField(upload_to="file/%Y", null=True, default="", verbose_name="文件")

    class Meta:
        db_table = 'file'
